// https://leetcode.cn/problems/merge-intervals/description/

// 算法思路总结：
// 1. 贪心策略处理区间合并问题
// 2. 按区间左端点排序，便于顺序合并
// 3. 维护当前合并区间的左右边界
// 4. 遍历时判断重叠：有重叠则更新右边界，无重叠则保存前一个区间
// 5. 时间复杂度：O(nlogn)，空间复杂度：O(n)

#include <iostream>
using namespace std;

#include <vector>
#include <algorithm>

class Solution 
{
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) 
    {
        int m = intervals.size();

        sort(intervals.begin(), intervals.end(), [](const vector<int>& v1, const vector<int>& v2){
            return v1[0] < v2[0];
        });

        vector<vector<int>> ret;
        int l = -1, r = -1;
        for (int i = 0 ; i < m ; i++)
        {
            if (intervals[i][1] <= r)
                continue;
            else if (intervals[i][0] <= r)
                r = intervals[i][1];        
            else
            {
                if (r != -1)
                    ret.push_back({l, r});
                l = intervals[i][0];
                r = intervals[i][1];
            }
        }
        ret.push_back({l, r});

        return ret;
    }
};

int main()
{
    vector<vector<int>> vv1 = {{1,3}, {2,6}, {8,10}, {15,18}};
    vector<vector<int>> vv2 = {{1,4}, {4,5}};

    Solution sol;

    auto r1 = sol.merge(vv1);
    auto r2 = sol.merge(vv2);

    for (auto& v : r1)
    {
        for (auto& num : v)
            cout << num << " ";
        cout << endl;
    }
    cout << endl;

    for (auto& v : r2)
    {
        for (auto& num : v)
            cout << num << " ";
        cout << endl;
    }

    return 0;
}